package com.itheima.util;

/**
 * @Author longbosheng
 * @Date 2022/6/19 9:35
 * @PackageName:com.itheima.util
 * @ClassName: OSSUtils
 * @Description: TODO
 * @Version 1.0
 */

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * OSS文件上传工具类
 */
public class OSSUtils {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
    private static String accessKeyId = "LTAI5tJ8GcERHytJcoEFxkCU";//
    private static String accessKeySecret = "JBV3LuGiibXxdslLYFv3mfsD1cvjBq";
    private static String bucketName = "reggie-longbosheng";

    private final static String URL = "\n" +
            "https://reggie-longbosheng.oss-cn-hangzhou.aliyuncs.com/";
    //目录名
    public static String dir = "dish/";

    /**
     * 文件上传
     *
     * @param inputStream
     * @param fileName
     */
    public static String upload(InputStream inputStream, String fileName) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.putObject(bucketName, dir + fileName, inputStream);

//        System.out.println(filename);
        oss.shutdown();
        String ossUrl = URL + dir + fileName;

        System.out.println("图片地址" + ossUrl);

        return ossUrl;
    }


    /**
     * 文件下载
     *
     * @param filename
     * @param response
     * @throws IOException
     */
    public static void download(String filename, HttpServletResponse response) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(bucketName, dir + filename);
        //通过输出流，输出文件内容
        ServletOutputStream outputStream = response.getOutputStream();
        //设置输出文件的格式
        response.setContentType("/image/jpeg");
        InputStream content = ossObject.getObjectContent();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = content.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        content.close();
    }
}
